package pl.ivmx.cinema;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ShowDao extends BaseDao {
	private static ShowDao instance = null;
	private List<ShowObserver> observers;

	private List<BasicEntity> notifications;
	private ThreadManager threadManager;
	private DaoThread daoThread;
	private EntityManager em;
	
	private ShowDao() {

		threadManager = ThreadManager.getInstance();
		notifications = new ArrayList<BasicEntity>();
		observers = new ArrayList<ShowObserver>();
		EntityManagerFactory emf = 
			Persistence.createEntityManagerFactory("cinemaJPA");
		em = emf.createEntityManager();
	}

	public static ShowDao getInstance() {
		if (instance == null) {
			instance = new ShowDao();
		}
		return instance;
	}

	@Override
	public void findNotifications() {
		System.out.println("Find nttification for SHOW");
		ResultSet newShows = JDBCConnection.getInstance().executeQuery(
				"Select * from LogShow");
		String showID;
		
		try {
			while (newShows.next()) {
				String logID = newShows.getString("id");
				showID = newShows.getString("show_id");
				System.out.println("Nowy idek SHOW: "+showID);
				
				ResultSet shows = JDBCConnection.getInstance().executeQuery(
						"Select * from show where id=" + showID);

				try {
					while (shows.next()) {

						//String showName = shows.getString("showName");
						Integer id = Integer.parseInt(shows.getString("id"));

						ShowEntity movie = new ShowEntity(id, "NARAZIE PUSTR");

						notifications.add(movie);

					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				JDBCConnection.getInstance().executeStatement("delete from LogShow where id = " + logID);
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void addListener(IObserver io) {
		if (io instanceof ShowObserver) {
			observers.add((ShowObserver) io);
			
		}
		
		if (observers.size() == 1 ){
			if (daoThread == null) {
				daoThread = (DaoThread) ThreadManager.getInstance().createThread(this);
				
			}
			ThreadManager.getInstance().start(daoThread);
		} 
	}

	@Override
	public void notifyListener() {
		for (BasicEntity be : notifications) {
			for (ShowObserver o : observers) {
				o.update(be);
			}
		}
		notifications.clear();
	}

	@Override
	public void removeListener(IObserver io) {
		if (io instanceof ShowObserver) {
			observers.remove((ShowObserver) io);
		}
		
		if (observers.size() == 0){
			if (daoThread != null){
				ThreadManager.getInstance().stopThread(daoThread);
			}
		}
	}

}
